package com.channel.temperature.collect.ui.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.hjq.toast.ToastUtils
import com.hjy.bluetooth.entity.BluetoothDevice
import com.inuker.bluetooth.library.Code.REQUEST_SUCCESS
import com.inuker.bluetooth.library.Constants.STATUS_CONNECTED
import com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener
import com.inuker.bluetooth.library.connect.options.BleConnectOptions
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse
import com.kongzue.dialogx.dialogs.BottomMenu
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener
import com.channel.temperature.collect.R
import com.channel.temperature.collect.app.base.BaseActivity
import com.channel.temperature.collect.app.ble.BLECommand
import com.channel.temperature.collect.app.ext.LiveDataEvent
import com.channel.temperature.collect.app.ext.initBack
import com.channel.temperature.collect.app.ext.mmkv
import com.channel.temperature.collect.app.util.ClientManager
import com.channel.temperature.collect.app.util.MyUtil
import com.channel.temperature.collect.data.annotation.ValueKey
import com.channel.temperature.collect.databinding.ActivityBleBinding
import com.channel.temperature.collect.ui.adapter.TipsAdapter
import com.channel.temperature.collect.ui.viewmodel.BLEModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.mvvmhelper.ext.divider
import me.hgj.mvvmhelper.ext.getColorExt
import me.hgj.mvvmhelper.ext.grid
import me.hgj.mvvmhelper.ext.setOnclickNoRepeat
import me.hgj.mvvmhelper.ext.toStartActivity
import me.hgj.mvvmhelper.util.decoration.DividerOrientation
import java.util.UUID


class BLEActivity : BaseActivity<BLEModel, ActivityBleBinding>() {
    companion object {
        const val TAG = "BLEActivity"
        val baudsList = mutableListOf<String>(
            "9600", "14400", "19200", "38400", "57600", "115200", "230400", "460800", "921600"
        )
        val baudsValueList = mutableListOf<Byte>(
            0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
        )
        val tcCmdList = mutableListOf<String>(
            "进入透传",
            "退出透传",
            "测试命令",
            "设置HC-04S波特率",
            "查询SPP蓝牙地址",
            "查询BLE蓝牙地址",
            "设置SPP蓝牙名字",
            "设置BLE蓝牙名字",
        )

        //锁具UUID
        val RX_SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
        val RX_CHAR_UUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e") //写数据，从手机的角度

        val TX_CHAR_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e") //读数据

    }

    var continueSendBaud: Boolean = false

    var isBLECMDClick = true
    var canSubString = false
    var subStringResult: String = ""
    private val mTipsAdapter: TipsAdapter by lazy { TipsAdapter() }
    private var mMac: String? = ""
    private var mName: String? = ""
    private var mConnected = false
    private val mBleConnectStatusListener: BleConnectStatusListener =
        object : BleConnectStatusListener() {
            override fun onConnectStatusChanged(mac: String, status: Int) {
                if (status == STATUS_CONNECTED) {
//                    mViewModel.addMessage(mName + "连接成功")
                    mConnected = true
                    openNotify(mac, RX_SERVICE_UUID, TX_CHAR_UUID)
                } else if (status == STATUS_DISCONNECTED) {
                    mViewModel.addMessage(mName + "检测已断开")
                    Log.e("蓝牙连接状态", "检测已断开连接 $mName")
                    mConnected = false
                    closeNotify(mac, RX_SERVICE_UUID, TX_CHAR_UUID)

                }
            }
        }

    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack("无线传输工具设置") {
            finish()
        }

        mToolbar.setRightDrawable(R.drawable.ic_bluetooth_black_24dp)
        //初始化 recycleView
        mBind.listRecyclerView.grid(1).divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setDivider(0, true)
            setColor(getColorExt(R.color.common_text_hint_color))
        }.adapter = mTipsAdapter
        initDataLayout()
    }


    private fun initDataLayout() {
        mBind.sleepTime.setText(mmkv.getString(ValueKey.sleepTime, "5") + "")
        mBind.chooseBaudNumber.setText("" + mmkv.getString(ValueKey.baudValue, "9600"))
        mBind.chooseHC04BaudNumber.setText("" + mmkv.getString(ValueKey.baudValue, "9600"))
        mBind.setENToggle.text =
            if (mmkv.getBoolean(ValueKey.enValue, false)) "设备开机" else "设备关机"
        mBind.set9700Toggle.text =
            if (mmkv.getBoolean(ValueKey.open9700Value, false)) "设备供电开" else "设备供电关"

        mBind.BleLayout.visibility = View.VISIBLE
        mBind.ATLayout.visibility = View.GONE
        mBind.sppDevNameET.setText(mmkv.getString(ValueKey.editSPPDevName, ""))
        mBind.bleDevNameET.setText(mmkv.getString(ValueKey.editBLEDevName, ""))
        mBind.configATCMDET.setText(mmkv.getString(ValueKey.configATCMD, ""))
        mBind.setENToggle.isChecked = false
        mBind.setENToggle.text = "设备关机"
        mBind.set9700Toggle.isChecked = false
        mBind.set9700Toggle.text = "设备供电关"
        mBind.setENToggle.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Log.e("onCheckedChanged", "onCheckedChanged : $isChecked")
            if (isChecked) {
                mBind.setENToggle.text = "设备开机"
            } else {
                mBind.setENToggle.text = "设备关机"
            }
            if (mConnected) {
                mMac?.let { it1 ->
                    mViewModel.sendVOUTCMD(
                        it1,
                        mBind.setENToggle.isChecked,
                        mBind.set9700Toggle.isChecked
                    )
                }

            } else {
                ToastUtils.show("请先连接设备后再操作")
            }
        })
        mBind.set9700Toggle.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Log.e("onCheckedChanged", "onCheckedChanged : $isChecked")
            if (isChecked) {
                mBind.set9700Toggle.text = "设备供电开"
            } else {
                mBind.set9700Toggle.text = "设备供电关"
            }
            if (mConnected) {
                mMac?.let { it1 ->
                    mViewModel.sendVOUTCMD(
                        it1,
                        mBind.setENToggle.isChecked,
                        mBind.set9700Toggle.isChecked
                    )
                }

            } else {
                ToastUtils.show("请先连接设备后再操作")
            }
        })
    }

    override fun onBindViewClick() {
        //绑定点击事件
        setOnclickNoRepeat(
            mToolbar.getRightId(),
            mBind.setSleepTime,
            mBind.clearTips,
            mBind.chooseBaudNumber,
            mBind.setENToggle,
            mBind.set9700Toggle,
            mBind.setBaudNumber,
//            mBind.setOnOffCmd,
            mBind.queryElect,
            mBind.queryElectInterval,
            mBind.tcOnSet,
            mBind.changeToBleLayout,
            mBind.tcon,
            mBind.tcoff,
            mBind.testTCCmd,
            mBind.querySPPMac,
            mBind.queryBLEMac,
            mBind.chooseHC04BaudNumber,
            mBind.setHC04BaudNumber,
            mBind.setSPPDevName,
            mBind.setbleDevName,
            mBind.clearTips2,
            mBind.sendConfigAT,
            mBind.checkCMD,
            mBind.serialPort,
            mBind.deviceInfo
        ) {
            mViewModel.clickType = -1
            canSubString = false
            subStringResult = ""
            continueSendBaud = false
            when (it) {
                mToolbar.getRightId() -> {
                    //如果已经连接了设备 点击则断开连接
                    ClientManager.getClient().disconnect(mMac);
                    var bund = Bundle()
                    bund.putInt(ValueKey.DeviceType, 2)
                    toStartActivity(DeviceListActivity::class.java, bund)
                }

                mBind.serialPort -> {
                    if (mConnected) {
                        mMac?.let { it1 ->

                            if (!mBind.serialPortCMDET.text.toString().trim()
                                    .isNullOrBlank() && mBind.serialPortCMDET.text.toString().trim()
                                    .toInt() > 0 && mBind.serialPortCMDET.text.toString().trim()
                                    .toInt() < 255
                            ) {
                                Log.e(
                                    "转换",
                                    "转换 ：" + mBind.serialPortCMDET.text.toString().trim().toInt()
                                )
                                mViewModel.sendSerialPortCMD(
                                    it1, mBind.serialPortCMDET.text.toString().trim().toInt()
                                )
                            } else {
                                ToastUtils.show("串口命令编辑框的值应在0-254之间")
                            }

                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.deviceInfo -> {
                    if (mConnected) {
                        mMac?.let { it1 ->
                            mViewModel.sendQueryDeviceInfoCMD(
                                it1
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.setSleepTime -> {
                    mmkv.putString(ValueKey.sleepTime, mBind.sleepTime.text.toString().trim())
                    if (mConnected) {
                        mMac?.let { it1 ->
                            mViewModel.sendSleepTimeCMD(
                                it1, mBind.sleepTime.text.toString().trim().toInt()
                            )
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.checkCMD -> {
                    if (mConnected) {
                        if (mBind.checkCMDET1.text.toString()
                                .trim() == "" || mBind.checkCMDET2.text.toString().trim() == ""
                        ) {
                            ToastUtils.show("请输入参数再操作")
                        } else {
                            mViewModel.sendValue1 = mBind.checkCMDET1.text.toString().trim().toInt()
                            mViewModel.sendValue2 = mBind.checkCMDET2.text.toString().trim().toInt()
                            mMac?.let { it1 ->
                                mViewModel.sendCheckCMD(
                                    it1,
                                    mBind.checkCMDET1.text.toString().trim().toInt(),
                                    mBind.checkCMDET2.text.toString().trim().toInt()
                                )
                            }
                        }

                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.clearTips -> {
                    mViewModel.clearTips()
                }

                mBind.chooseBaudNumber -> {
                    BottomMenu.show(baudsList as List<CharSequence>?)
                        .setMessage("请选择波特率").onMenuItemClickListener =
                        OnMenuItemClickListener { dialog, text, index ->
                            mBind.chooseBaudNumber.text = baudsList.get(index)
                            mBind.chooseHC04BaudNumber.text = baudsList.get(index)
                            mmkv.putString(ValueKey.baudValue, baudsList.get(index))
                            mmkv.putInt(ValueKey.baudValueBle, baudsValueList.get(index).toInt())
                            false
                        }
                }

                mBind.chooseHC04BaudNumber -> {
                    BottomMenu.show(baudsList as List<CharSequence>?)
                        .setMessage("请选择波特率").onMenuItemClickListener =
                        OnMenuItemClickListener { dialog, text, index ->
                            mBind.chooseBaudNumber.text = baudsList.get(index)
                            mBind.chooseHC04BaudNumber.text = baudsList.get(index)
                            mmkv.putString(ValueKey.baudValue, baudsList.get(index))
                            mmkv.putInt(ValueKey.baudValueBle, baudsValueList.get(index).toInt())
                            false
                        }
                }

//                mBind.setENToggle -> {
//                    if (mConnected) {
//                        if (mBind.setENToggle.text.equals("设备开机")) {
//
//                            mMac?.let { it1 ->
//                                mViewModel.sendVOUTCMD(it1)
//                                mBind.setENToggle.setText("设备关机")
//                                mmkv.putBoolean(ValueKey.enValue, false)
//                            }
//                        } else {
//
//                            mMac?.let { it1 ->
//                                mViewModel.sendVOUTCMD(it1)
//                                mBind.setENToggle.setText("设备开机")
//                                mmkv.putBoolean(ValueKey.enValue, true)
//                            }
//                        }
//
//
//                        mMac?.let { it1 -> mViewModel.sendVOUTCMD(it1) }
//                    } else {
//                        ToastUtils.show("请先连接设备后再操作")
//                    }
//
//
//                }
//
//                mBind.set9700Toggle -> {
//                    if (mConnected) {
//                        if (mBind.set9700Toggle.text.equals("设备供电开")) {
//                            mMac?.let { it1 ->
//                                mViewModel.sendVOUTCMD(it1)
//                                mBind.set9700Toggle.setText("设备供电关")
//                                mmkv.putBoolean(ValueKey.open9700Value, false)
//                            }
//
//                        } else {
//                            mMac?.let { it1 ->
//                                mViewModel.sendVOUTCMD(it1)
//                                mBind.set9700Toggle.setText("设备供电开")
//                                mmkv.putBoolean(ValueKey.open9700Value, true)
//                            }
//
//                        }
//
//                    } else {
//                        ToastUtils.show("请先连接设备后再操作")
//                    }
//
//
//                }

//                mBind.setOnOffCmd -> {
//                    if (mConnected) {
//                        mMac?.let { it1 -> mViewModel.sendVOUTCMD(it1) }
//                    } else {
//                        ToastUtils.show("请先连接设备后再操作")
//                    }
//                }

                mBind.setBaudNumber -> {
                    var baudValue = mmkv.getInt(ValueKey.baudValueBle, 3)
                    Log.e("发送的波特率值", "发送的波特率值 " + baudValue)
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendBaudCMD(it1, baudValue) }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }


                mBind.queryElect -> {
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendQueryElectCMD(it1) }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.queryElectInterval -> {
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendQueryElectCMD(it1) }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.tcOnSet -> {
                    isBLECMDClick = false
                    mBind.BleLayout.visibility = View.GONE
                    mBind.ATLayout.visibility = View.VISIBLE
                }

                mBind.changeToBleLayout -> {
                    isBLECMDClick = true
                    mBind.BleLayout.visibility = View.VISIBLE
                    mBind.ATLayout.visibility = View.GONE
                }

                mBind.tcon -> {
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "tcon") }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.tcoff -> {
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "tcoff") }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.testTCCmd -> {
                    if (mConnected) {
                        mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "AT") }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.sendConfigAT -> {
                    if (mConnected) {
                        if (mBind.configATCMDET.text.toString().trim().length in 1..18) {
                            mMac?.let { it1 ->
                                mViewModel.sendShortTCCmd(
                                    it1, mBind.configATCMDET.text.toString()
                                )
                            }
                        } else if (mBind.configATCMDET.text.toString().trim().length in 19..20) {
                            mMac?.let { it1 ->
                                lifecycleScope.launch {
                                    mViewModel.sendShortTCCmd(
                                        it1, mBind.configATCMDET.text.toString().trim(), false
                                    )
                                    delay(300)
                                    mViewModel.send0D0A(it1)
                                }
                            }
                        }


                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.setSPPDevName -> {
                    if (mConnected) {
                        mMac?.let { it1 ->
                            Log.e("测试", "测试   " + mBind.sppDevNameET.text.toString())
                            lifecycleScope.launch {
                                mViewModel.sendShortTCCmd(
                                    it1,
                                    "AT+NAME=TZWM23S-" + mBind.sppDevNameET.text.toString().trim(),
                                    false
                                )
                                delay(300)
                                mViewModel.send0D0A(it1)
                            }
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.setbleDevName -> {
                    if (mConnected) {
                        lifecycleScope.launch {
                            mMac?.let { it1 ->
                                mViewModel.sendShortTCCmd(
                                    it1, "AT+BNAME=TZWM23B-", false
                                )
                                delay(300)
                                mViewModel.sendShortTCCmd(
                                    it1, mBind.bleDevNameET.text.toString().trim(), true
                                )
                            }
                        }

                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.querySPPMac -> {
                    if (mConnected) {
                        mViewModel.clickType = 1
                        canSubString = false
                        subStringResult = ""
                        mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "AT+ADDR=?") }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.queryBLEMac -> {
                    if (mConnected) {
                        mViewModel.clickType = 2
                        canSubString = false
                        subStringResult = ""
                        mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "AT+BADDR=?") }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }

                mBind.clearTips2 -> {
                    mViewModel.clearTips()
                }

                mBind.setHC04BaudNumber -> {
                    var baudValue = mmkv.getString(ValueKey.baudValue, "9600")
                    Log.e("发送的波特率值", "发送的波特率值 $baudValue")
                    if (mConnected) {
                        continueSendBaud = true
                        mViewModel.clickType = 3
                        mMac
                        mMac?.let { it1 ->
                            baudValue?.let { it2 ->
                                mViewModel.sendShortTCCmd(
                                    it1, "AT+BAUD=" + it2
                                )
                            }
                        }
                    } else {
                        ToastUtils.show("请先连接设备后再操作")
                    }
                }
            }
        }
    }


    override fun onRequestSuccess() {
        LiveDataEvent.connectBleDevice.observe(this, Observer {
            if (LiveDataEvent.connectBleDevice.value?.connect == true) {
                mMac = it.bluetoothDevice?.address
                mName = it.bluetoothDevice?.name
                connectDevice(LiveDataEvent.connectBleDevice.value!!.bluetoothDevice as BluetoothDevice)
            }
        })
        mViewModel.tipslistData.observe(this, Observer {
            mTipsAdapter.setNewInstance(it)
            mTipsAdapter.notifyDataSetChanged()
            mBind.listRecyclerView.layoutManager?.scrollToPosition(mTipsAdapter.itemCount - 1)
        })
        mViewModel.continueSendTCON.observe(this, Observer {
            if (it) {
                mViewModel.clickType = 3
                mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "tcon") }
            }
        })
    }

    private fun connectDevice(bluetoothDevice: BluetoothDevice?) {
        Log.e("connectDevice", "connectDevice    " + bluetoothDevice?.name)
        if (!mConnected) {
            ClientManager.getClient().registerConnectStatusListener(mMac, mBleConnectStatusListener)
            val options = BleConnectOptions.Builder().setConnectRetry(1) // 连接如果失败重试3次
                .setConnectTimeout(5000) // 连接超时5s
                .setServiceDiscoverRetry(1) // 发现服务如果失败重试3次
                .setServiceDiscoverTimeout(5000) // 发现服务超时5s
                .build()

            ClientManager.getClient().connect(
                mMac, options
            ) { code, data ->
                if (code == REQUEST_SUCCESS) {
                    mViewModel.addMessage(bluetoothDevice?.name.toString() + "连接成功")
                    try {
                        Thread.sleep(200)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                } else {
                    mViewModel.addMessage(bluetoothDevice?.name.toString() + "连接失败")
                    Toast.makeText(
                        applicationContext, "连接失败,请重启蓝牙", Toast.LENGTH_SHORT
                    ).show()
                    ClientManager.getClient().disconnect(mMac)
                }
            }

        }

    }

    //关闭notify
    private fun closeNotify(MAC: String, serviceUUID: UUID, characterUUID: UUID) {
        ClientManager.getClient()
            .unnotify(MAC, serviceUUID, characterUUID, BleUnnotifyResponse { code ->
                Log.e("unnotify", "unnotify  $code")
                if (code == REQUEST_SUCCESS) {
//                    mViewModel.addMessage(mName + "关闭notify")
                }
            })
    }

    //打开notification通知
    private fun openNotify(MAC: String, serviceUUID: UUID, characterUUID: UUID) {
        ClientManager.getClient()
            .notify(MAC, serviceUUID, characterUUID, object : BleNotifyResponse {
                override fun onNotify(service: UUID, character: UUID, result: ByteArray) {
                    if (isBLECMDClick) {
                        mViewModel.addMessage(
                            "返回数据->" + MyUtil.bytes2Hex(
                                BLECommand.decodeRC4Bytes(
                                    result
                                )
                            )
                        )
                        mViewModel.handleBLEResult(BLECommand.decodeRC4Bytes(result))
                    } else {
                        mViewModel.addMessage("返回数据->" + MyUtil.bytetoString(result))
                        if (mViewModel.clickType == 1) {
                            var subStringResultData = MyUtil.bytetoString(result)
                            if (!canSubString) {
                                if (subStringResultData.contains("OK+ADDR=04")) {
                                    canSubString = true
                                    subStringResult = subStringResultData
                                }
                            } else {
                                subStringResult += MyUtil.bytetoString(result)
                                mViewModel.addMessage("组合后的完整数据->" + subStringResult)
                                CoroutineScope(Dispatchers.Main).launch {
                                    var nameTemp = subStringResult.substring(
                                        subStringResult.length - 6, subStringResult.length - 1
                                    )
                                    var result = nameTemp.substring(2, 4) + nameTemp.substring(0, 2)
                                    mBind.sppDevNameET.setText(
                                        result
                                    )
                                }
                            }
                        } else if (mViewModel.clickType == 2) {
                            var subStringResultData = MyUtil.bytetoString(result)
                            if (!canSubString) {
                                if (subStringResultData.contains("OK+BADDR=C4")) {
                                    canSubString = true
                                    subStringResult = subStringResultData
                                }
                            } else {
                                subStringResult += MyUtil.bytetoString(result)
                                mViewModel.addMessage("组合后的完整数据->" + subStringResult)
                                CoroutineScope(Dispatchers.Main).launch {
                                    var nameTemp = subStringResult.substring(
                                        subStringResult.length - 6, subStringResult.length - 1
                                    )
                                    var result = nameTemp.substring(2, 4) + nameTemp.substring(0, 2)
                                    mBind.bleDevNameET.setText(
                                        result
                                    )
                                }
                            }
                        } else if (mViewModel.clickType == 3) {
                            var dataResult = MyUtil.bytetoString(result)

                            lifecycleScope.launch {
                                if (dataResult.contains("OK+BAUD=") && dataResult.split("=").get(1)
                                        .contains(
                                            mmkv.getString(
                                                ValueKey.baudValue, "9600"
                                            ).toString()
                                        )
                                ) {
                                    delay(30)
                                    mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "tcoff") }
                                } else if (dataResult.contains("tcoff")) {
                                    delay(30)
                                    var baudValue = mmkv.getInt(ValueKey.baudValueBle, 3)
                                    mViewModel.clickType = 4
                                    mMac?.let { it1 -> mViewModel.sendBaudCMD(it1, baudValue) }
                                } else if (dataResult.contains("tcon")) {
                                    delay(30)
                                    mMac?.let { it1 -> mViewModel.sendShortTCCmd(it1, "AT") }
                                } else if (dataResult.contains("OK")) {
                                    delay(30)
                                    mViewModel.addMessage("设置无线传输波特率成功")
                                    mViewModel.clickType = -1
                                }
                            }

                        } else if (mViewModel.clickType == 4) {
                            mViewModel.addMessage(
                                "返回数据->" + MyUtil.bytes2Hex(
                                    BLECommand.decodeRC4Bytes(
                                        result
                                    )
                                )
                            )
                            mViewModel.handleBLEResult(BLECommand.decodeRC4Bytes(result))
                        }
                    }
                }

                override fun onResponse(code: Int) {
                    if (code == REQUEST_SUCCESS) {
                        Log.e(TAG, "notify-onresponse 打开通知成功")
                        mViewModel.addMessage("打开通知成功")
                    } else {
                        mViewModel.addMessage("打开通知失败")
                    }
                }
            })
    }


    override fun onDestroy() {
        super.onDestroy()
        mMac?.let {
            ClientManager.getClient().disconnect(mMac)
        }

    }
}